<template>
  <div class="m-auto" v-loading="loading" :style="{ width: `${column * 73 + column * gap * 3}px` }">
    <div class="flex justify-between items-center gap-10px mb-10px">
      <div> 提示：空白区域需设置为空白块 </div>
      <div>
        <a-button type="primary" @click="handleOk">保存</a-button>
        <a-button type="primary" @click="handleCreate" class="ml-2">新增</a-button>
        <a-button type="primary" @click="handleClear" class="ml-2">清除</a-button>
      </div>
    </div>
    <div
      class="relative"
      :style="{ backgroundColor: 'transparent', height: `${row * 78 + row * gap}px` }"
    >
      <div class="grid-container">
        <div class="grid-item" v-for="item in row * column" :key="'grid' + item"></div>
      </div>
      <grid-layout
        v-model:layout="layoutList"
        :col-num="column"
        :row-height="73"
        :is-draggable="true"
        :is-resizable="true"
        :is-mirrored="false"
        :vertical-compact="true"
        :margin="[4, 6]"
        :use-css-transforms="true"
        :max-rows="row"
        @layout-updated="handleLayoutUpdated"
      >
        <grid-item
          v-for="(item, index) in layoutList"
          :key="`${item?.i}`"
          :drag-allow-from="`.toolbox`"
          :i="item.i"
          :x="item.x"
          :y="item.y"
          :w="item.w"
          :h="item.h"
          :minW="item.minW"
          :maxH="item.maxH"
          :minH="item.minH"
          :static="item.static"
        >
          <div
            class="h-full p-2 flex flex-col relative"
            :style="{
              backgroundColor: item?.record?.bgColor || '#fff',
              boxShadow: '1px 1px 5px rgba(0, 0, 0, 0.8)',
              borderRadius: '6px',
            }"
            @dblclick="handleItem(item, index)"
          >
            <div class="flex justify-between absolute top-5px right-8px left-5px">
              <Icon icon="ant-design:drag-outlined" :class="`toolbox`" />
              <Icon
                icon="ant-design:close-outlined"
                @click="delDrag(item, index)"
                class="cursor-pointer font-bold"
              />
            </div>
            <div
              class="flex-1 flex items-center"
              :class="{
                'justify-center': item?.record?.align == 'center',
                'justify-start': item?.record?.align == 'left',
                'justify-end': item?.record?.align == 'right',
              }"
              :style="{
                color: item?.record?.fontColor || 'rgba(0,0,0,.9)',
                fontSize: item?.record?.fontSize || '14px',
                fontWeight: item?.record?.isBold == 'true' ? 'bold' : '',
              }"
            >
              {{
                item?.record?.type === 'button'
                  ? item?.record?.btnName
                  : item?.record?.innerHtml || item?.record?.label
              }}
            </div>
          </div>
        </grid-item>
      </grid-layout>
      <ListComponentModal
        @register="registerPhoneComponentModal"
        @success="handlePhoneComponentModalCallBack"
      />
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, h, onMounted, watch, nextTick } from 'vue';
  import { GridLayout, GridItem } from '/@/components/GridLayout';
  import Icon from '/@/components/Icon/index';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ListComponentModal from '../listComponent/ListComponentModal.vue';
  import { cloneDeep } from 'lodash-es';
  import {
    getVisualGetMobileListPageSetup,
    getVisualUpdatePageMobileList,
  } from '/@/api/module/module';
  import { getData, setData } from '../listComponent/listComponentModal.data';
  import { buildUUID } from '/@/utils/uuid';

  export default defineComponent({
    name: 'PhoneComponent',
    components: {
      GridLayout,
      GridItem,
      Icon,
      ListComponentModal,
    },
    props: {
      formCode: {
        type: String,
        default: '',
      },
      moduleCode: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      const { createConfirm, createMessage } = useMessage();
      const loading = ref(false);
      const layoutList = ref<any[]>([]);
      // { x: 0, y: 0, w: 1, h: 1, i: '0', static: false, minH: 5, type: 'grid' },
      layoutList.value = [];
      const layoutItem = ref({
        x: 0,
        y: 0,
        w: 1,
        h: 1,
        i: '0',
        static: false,
        minH: 1,
        maxH: 1,
        record: {
          blockId: buildUUID(22),
          align: 'left',
          x: 0,
          y: 0,
          fontColor: '#c9c9c9',
          bgColor: '#c9c9c9',
        },
      });
      const column = ref(6);
      const row = ref(6);
      const gap = ref(2);
      const gridGap = `${gap.value}px`;
      const [registerPhoneComponentModal, { openModal }] = useModal();

      const handlePhoneComponentModalCallBack = () => {
        fetch();
      };

      const handleItem = (item: Recordable, index) => {
        openModal(true, {
          isUpdate: true,
          record: item,
          formCode: props.formCode,
          moduleCode: props.moduleCode,
          layoutList: layoutList.value,
          currentItemIndex: index,
          column: column.value,
          type: 'phone',
        });
      };
      const delDrag = (record: Recordable, index) => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '确定删除吗？'),
          onOk: async () => {
            layoutList.value = layoutList.value.filter((_, i) => i != index);
            layoutList.value.forEach((item, i) => {
              item.i = i;
            });
            layoutList.value = [...layoutList.value];
          },
        });
      };

      //新增
      const handleCreate = () => {
        //layoutList.value顺序是不变的，拖动后顺序也不变
        let i = layoutList.value.length;
        let item: Recordable = cloneDeep(layoutItem.value);
        if (i != 0) {
          const lastItem = cloneDeep(layoutList.value[i - 1]);
          if (lastItem.x + lastItem.w == column.value) {
            item.x = 0;
            item.y = Number(lastItem.y) + Number(lastItem.h);
          } else {
            item.x = Number(lastItem.x) + Number(lastItem.w);
            item.y = lastItem.y;
          }
          item.i = i;
          item.minH = 1;
          item.maxH = 1;
          item.record = {
            blockId: buildUUID(22),
            align: 'left',
            x: item.x,
            y: item.y,
            fontColor: '#c9c9c9',
            bgColor: '#c9c9c9',
          };
        }
        //行不能超过row 列不能超过column
        if (item.x + item.w > column.value || item.y + item.h > row.value) {
          return;
        }
        layoutList.value.push(item);
      };
      //清除
      const handleClear = () => {
        layoutList.value = [];
      };

      const handleOk = async () => {
        try {
          const data = setData(layoutList.value, column.value);
          const formData = {
            moduleCode: props.moduleCode,
            widgets: JSON.stringify(data),
          };
          loading.value = true;
          let form = new FormData();
          for (let v in formData) {
            const value = formData[v] == null || formData[v] == undefined ? '' : formData[v];
            form.append(v, value);
          }
          await getVisualUpdatePageMobileList(form);
          fetch();
          createMessage.success('操作成功');
        } catch (error) {
          console.error(error);
        } finally {
          loading.value = false;
        }
      };

      const fetch = async () => {
        await nextTick();
        try {
          layoutList.value = [];
          const res = await getVisualGetMobileListPageSetup({ moduleCode: props.moduleCode });
          const data = getData(res);
          layoutList.value = data;
        } catch (error) {
          console.error(error);
        }
      };
      onMounted(fetch);

      const handleLayoutUpdated = (layout) => {};
      return {
        layoutList,
        column,
        row,
        gap,
        gridGap,
        delDrag,
        handleItem,
        registerPhoneComponentModal,
        handlePhoneComponentModalCallBack,
        handleCreate,
        handleClear,
        loading,
        handleOk,
        handleLayoutUpdated,
      };
    },
  });
</script>
<style lang="less" scoped>
  .grid-container {
    position: absolute;
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-columns: repeat(v-bind(column), 1fr); /* 创建12列 fr*/
    grid-gap: v-bind(gridGap); /* 设置列与列之间的间距 */
    padding: 2px;
    background-color: #1565a4;
  }
  // rgb(60, 111, 121) #3c6f79 #717378
  .grid-item {
    background-color: #000012;
    padding: 20px;
    text-align: center;
  }

  //拖拽阴影
  :deep(.vue-grid-placeholder) {
    background-color: rgb(9, 96, 189, 0.1);
  }
</style>
